package sum.achilles.com.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.Date;
import java.util.List;

import de.greenrobot.dao.query.DeleteQuery;
import de.greenrobot.dao.query.QueryBuilder;

public class DBHelper {

    private static final String DB_NAME = "sum-db";
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private static Context mContext;
    private static DBHelper instance;

    private static SQLiteDatabase db;

    private UserInfoDao userInfoDao;
    private NoteInfoDao noteInfoDao;

    public DBHelper() {
        // TODO Auto-generated constructor stub
    }

    //获取DBHelper对象
    public static DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper();
            if (mContext == null) {
                mContext = context;
            }

            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            db = helper.getWritableDatabase();
            daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();

            instance.userInfoDao = daoSession.getUserInfoDao();
            instance.noteInfoDao = daoSession.getNoteInfoDao();
        }
        return instance;
    }

    public void add_NoteInfo2DB(NoteInfo noteInfo) {
        noteInfoDao.insertOrReplace(noteInfo);
    }

    public List<NoteInfo> get_NoteInfo_all() {
        return noteInfoDao.loadAll();
    }

    public void del_noteInfo_all() {
        noteInfoDao.deleteAll();
    }

    public void del_noteInfo_byDate(Date date) {
        QueryBuilder<NoteInfo> qb = noteInfoDao.queryBuilder();
        DeleteQuery<NoteInfo> bd = qb.where(NoteInfoDao.Properties.Date.eq(date)).buildDelete();
        bd.executeDeleteWithoutDetachingEntities();
        noteInfoDao.deleteByKey(date);
    }

    public void del_noteInfo(NoteInfo noteInfo) {
        noteInfoDao.delete(noteInfo);
    }

    /**
     * --------------------------------------------------添加数据-------------------------------
     */
    public void add_UserInfo2DB(UserInfo userInfo) {
        userInfoDao.insertOrReplace(userInfo);
    }


    /** --------------------------------------------------获取数据-------------------------------*/
    /**
     * 该表只有一个用户
     */
    public UserInfo get_UserInfo4DB_by_first() {
        List<UserInfo> userInfos = userInfoDao.loadAll();
        return userInfos.size() == 0 ? null : userInfos.get(0);
    }


}
